<script setup>
    import { onMounted, ref } from 'vue'
    import { useRouter } from 'vue-router'
    import { useUserStore } from '@/stores/user'
    import { ElDialog, ElMessage } from 'element-plus'
    import { Edit, Refresh, Star, Trophy, Upload } from '@element-plus/icons-vue'
    import axios from 'axios'

    const router = useRouter()
    const userStore = useUserStore()

    // 当前头像URL
    const avatarUrl = ref('')

    // 游戏数据
    const gameStats = ref({
        gamesPlayed: 128,
        wins: 76,
        losses: 52,
        winRate: '59.4%',
        highestRating: 2450,
        currentStreak: 3,
    })

    // 编辑用户名对话框
    const editDialogVisible = ref(false)
    const newUsername = ref('')

    // 上传头像对话框
    const uploadAvatarDialogVisible = ref(false)
    const avatarFile = ref(null)
    const previewUrl = ref('')

    // 返回主菜单
    const goBack = () => {
        router.push('/')
    }

    // 打开编辑用户名对话框
    const openEditDialog = () => {
        newUsername.value = userStore.username
        editDialogVisible.value = true
    }

    // 提交用户名修改
    const submitUsernameChange = async () => {
        if (!newUsername.value.trim()) {
            ElMessage.error('用户名不能为空')
            return
        }

        try {
            const response = await axios.post(
                'http://127.0.0.1:8080/api/user/account/update-username/',
                { newUsername: newUsername.value },
                {
                    headers: {
                        Authorization: 'Bearer ' + userStore.token,
                    },
                }
            )

            const result = response.data
            if (result.code === 1) {
                ElMessage.success('用户名修改成功')
                userStore.username = newUsername.value
                editDialogVisible.value = false
            } else {
                ElMessage.error(result.msg || '用户名修改失败')
            }
        } catch (error) {
            console.error('修改用户名错误:', error)
            ElMessage.error('用户名修改失败，请稍后重试')
        }
    }

    // 打开上传头像对话框
    const openUploadAvatarDialog = () => {
        avatarFile.value = null
        previewUrl.value = ''
        uploadAvatarDialogVisible.value = true
    }

    // 处理头像文件选择
    const handleAvatarChange = (event) => {
        const file = event.target.files[0]
        if (!file) return

        // 验证文件类型
        const fileType = file.type
        if (!fileType.includes('image')) {
            ElMessage.error('请上传图片文件')
            return
        }

        // 验证文件大小，限制为2MB
        if (file.size / 1024 / 1024 > 2) {
            ElMessage.error('图片大小不能超过2MB')
            return
        }

        avatarFile.value = file

        // 创建预览URL
        const reader = new FileReader()
        reader.onload = (e) => {
            previewUrl.value = e.target.result
        }
        reader.readAsDataURL(file)
    }

    // 上传头像
    const uploadAvatar = async () => {
        if (!avatarFile.value) {
            ElMessage.error('请选择头像图片')
            return
        }

        const formData = new FormData()
        formData.append('file', avatarFile.value)

        try {
            ElMessage.info('正在上传头像...')

            const response = await axios.post(
                'http://127.0.0.1:8080/api/user/account/upload/',
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        Authorization: 'Bearer ' + userStore.token,
                    },
                }
            )

            const result = response.data
            console.log('上传头像返回数据:', result)

            if (result.code === 1) {
                // 检查返回数据结构
                console.log('头像URL数据:', result.data)

                // 根据返回数据结构获取头像URL
                let newAvatarUrl = result.data
                if (typeof result.data === 'object' && result.data.data) {
                    newAvatarUrl = result.data.data
                }

                console.log('新头像URL:', newAvatarUrl)

                // 更新用户头像
                userStore.photo = newAvatarUrl
                // 更新当前页面显示的头像URL
                avatarUrl.value = newAvatarUrl

                // 如果头像还是没显示，可以尝试强制刷新
                setTimeout(() => {
                    const timestamp = new Date().getTime()
                    // 添加时间戳参数强制浏览器刷新缓存
                    avatarUrl.value = newAvatarUrl + '?t=' + timestamp
                }, 100)

                ElMessage.success('头像上传成功')
                uploadAvatarDialogVisible.value = false
            } else {
                ElMessage.error(result.msg || '头像上传失败')
            }
        } catch (error) {
            console.error('上传头像错误:', error)
            ElMessage.error('头像上传失败，请稍后重试')
        }
    }

    // 刷新用户数据
    const refreshUserData = () => {
        ElMessage.info('正在刷新数据...')

        userStore.getinfo({
            success: () => {
                // 更新头像URL
                avatarUrl.value = userStore.photo
                ElMessage.success('数据已更新')
            },
            error: (err) => {
                ElMessage.error('数据更新失败')
                console.error(err)
            },
        })
    }

    onMounted(() => {
        // 从服务器获取最新用户数据
        refreshUserData()
        // 初始化头像URL
        avatarUrl.value = userStore.photo
    })
</script>

<template>
    <div class="profile-container">
        <div class="profile-card">
            <div class="profile-header">
                <h1>个人中心</h1>
            </div>

            <div class="profile-content">
                <!-- 用户基本信息 -->
                <div class="profile-section">
                    <h2>账号信息</h2>
                    <div class="avatar-container">
                        <div class="avatar">
                            <img
                                :key="avatarUrl || userStore.photo"
                                :src="
                                    avatarUrl ||
                                    userStore.photo ||
                                    'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
                                "
                                alt="用户头像"
                            />
                            <div class="avatar-upload" @click="openUploadAvatarDialog">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                                <span>更换头像</span>
                            </div>
                        </div>
                        <div class="user-details">
                            <div class="username">
                                {{ userStore.username }}
                                <el-icon class="edit-icon" @click="openEditDialog">
                                    <Edit />
                                </el-icon>
                            </div>
                            <div class="user-id">用户ID: {{ userStore.id || 'Unknown' }}</div>
                            <div class="user-level">
                                等级: <span class="highlight">{{ userStore.level || 0 }}</span>
                            </div>
                            <div class="user-rating">
                                段位分: <span class="highlight">{{ userStore.rating || 0 }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 游戏统计数据 -->
                <div class="profile-section">
                    <h2>游戏数据</h2>
                    <div class="stats-grid">
                        <div class="stat-item">
                            <div class="stat-icon">
                                <el-icon>
                                    <Trophy />
                                </el-icon>
                            </div>
                            <div class="stat-value">{{ gameStats.gamesPlayed }}</div>
                            <div class="stat-label">总场次</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-icon win">
                                <span>W</span>
                            </div>
                            <div class="stat-value">{{ gameStats.wins }}</div>
                            <div class="stat-label">胜利</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-icon loss">
                                <span>L</span>
                            </div>
                            <div class="stat-value">{{ gameStats.losses }}</div>
                            <div class="stat-label">失败</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-icon">
                                <span>%</span>
                            </div>
                            <div class="stat-value">{{ gameStats.winRate }}</div>
                            <div class="stat-label">胜率</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-icon">
                                <el-icon>
                                    <Star />
                                </el-icon>
                            </div>
                            <div class="stat-value">{{ gameStats.highestRating }}</div>
                            <div class="stat-label">最高分</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-icon streak">
                                <span>🔥</span>
                            </div>
                            <div class="stat-value">{{ gameStats.currentStreak }}</div>
                            <div class="stat-label">连胜</div>
                        </div>
                    </div>
                </div>

                <!-- 最近游戏记录 -->
                <div class="profile-section">
                    <h2>最近战绩</h2>
                    <div class="match-history">
                        <div class="match-item win">
                            <div class="match-result">胜利</div>
                            <div class="match-details">
                                <div class="match-opponent">vs 玩家123</div>
                                <div class="match-score">3-1</div>
                            </div>
                            <div class="match-rating">+25</div>
                        </div>
                        <div class="match-item loss">
                            <div class="match-result">失败</div>
                            <div class="match-details">
                                <div class="match-opponent">vs 光速突袭者</div>
                                <div class="match-score">2-3</div>
                            </div>
                            <div class="match-rating">-15</div>
                        </div>
                        <div class="match-item win">
                            <div class="match-result">胜利</div>
                            <div class="match-details">
                                <div class="match-opponent">vs 星际战队</div>
                                <div class="match-score">3-0</div>
                            </div>
                            <div class="match-rating">+28</div>
                        </div>
                    </div>
                    <div class="history-footer">
                        <button class="history-btn">查看更多</button>
                        <button class="refresh-btn" @click="refreshUserData">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                            刷新数据
                        </button>
                    </div>
                </div>
            </div>

            <div class="profile-footer">
                <button class="back-btn" @click="goBack">返回主菜单</button>
            </div>
        </div>
    </div>

    <!-- 编辑用户名对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        :show-close="false"
        center
        class="edit-dialog"
        title="修改用户名"
        width="400px"
    >
        <div class="dialog-content">
            <div class="form-item">
                <label>新用户名</label>
                <input
                    v-model="newUsername"
                    maxlength="20"
                    placeholder="请输入新的用户名"
                    type="text"
                />
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <button class="dialog-btn cancel" @click="editDialogVisible = false">取消</button>
                <button class="dialog-btn confirm" @click="submitUsernameChange">确认修改</button>
            </div>
        </template>
    </el-dialog>

    <!-- 上传头像对话框 -->
    <el-dialog
        v-model="uploadAvatarDialogVisible"
        :show-close="false"
        center
        class="edit-dialog"
        title="更换头像"
        width="400px"
    >
        <div class="dialog-content">
            <div class="avatar-preview">
                <img
                    :key="previewUrl || avatarUrl || userStore.photo"
                    :src="
                        previewUrl ||
                        avatarUrl ||
                        userStore.photo ||
                        'https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg'
                    "
                    alt="头像预览"
                />
            </div>
            <div class="form-item">
                <label>选择图片</label>
                <input
                    accept="image/*"
                    class="file-input"
                    type="file"
                    @change="handleAvatarChange"
                />
            </div>
            <div class="upload-tips">支持JPG、PNG格式，文件大小不超过2MB</div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <button class="dialog-btn cancel" @click="uploadAvatarDialogVisible = false">
                    取消
                </button>
                <button class="dialog-btn confirm" @click="uploadAvatar">上传头像</button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
    .profile-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        width: 100vw;
    }

    .profile-card {
        width: 800px;
        background-color: rgba(0, 0, 0, 0.7);
        border-radius: 12px;
        padding: 30px;
        box-shadow: 0 0 30px rgba(255, 215, 0, 0.3);
        border: 1px solid rgba(255, 215, 0, 0.3);
        color: #fff;
        animation: fadeIn 0.5s ease-in-out;
        transform: scale(1);
        transition: transform 0.3s ease;
    }

    .profile-card:hover {
        transform: scale(1.01);
        box-shadow: 0 0 40px rgba(255, 215, 0, 0.5);
    }

    .profile-header {
        text-align: center;
        margin-bottom: 30px;
        border-bottom: 1px solid rgba(255, 215, 0, 0.3);
        padding-bottom: 15px;
    }

    .profile-header h1 {
        font-size: 28px;
        color: #ffd700;
        text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
        margin: 0;
        letter-spacing: 2px;
    }

    .profile-content {
        margin-bottom: 30px;
        max-height: 70vh;
        overflow-y: auto;
        padding-right: 10px;
    }

    .profile-content::-webkit-scrollbar {
        width: 6px;
    }

    .profile-content::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 3px;
    }

    .profile-content::-webkit-scrollbar-thumb {
        background-color: rgba(255, 215, 0, 0.5);
        border-radius: 3px;
    }

    .profile-section {
        margin-bottom: 25px;
        padding-bottom: 15px;
    }

    .profile-section:not(:last-child) {
        border-bottom: 1px solid rgba(255, 215, 0, 0.2);
    }

    .profile-section h2 {
        font-size: 20px;
        color: #ffd700;
        margin-bottom: 15px;
        padding-bottom: 8px;
    }

    /* 用户基本信息样式 */
    .avatar-container {
        display: flex;
        align-items: center;
        padding: 10px;
    }

    .avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        overflow: hidden;
        border: 3px solid #ffd700;
        box-shadow: 0 0 15px rgba(255, 215, 0, 0.5);
        position: relative;
    }

    .avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .avatar-upload {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        background: rgba(0, 0, 0, 0.6);
        color: white;
        padding: 5px 0;
        font-size: 12px;
        text-align: center;
        opacity: 0;
        transition: opacity 0.3s;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .avatar:hover .avatar-upload {
        opacity: 1;
    }

    .user-details {
        margin-left: 20px;
        flex: 1;
    }

    .username {
        font-size: 26px;
        font-weight: bold;
        color: #ffd700;
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }

    .edit-icon {
        margin-left: 10px;
        cursor: pointer;
        font-size: 16px;
        color: rgba(255, 255, 255, 0.6);
        transition: all 0.3s;
    }

    .edit-icon:hover {
        color: #ffd700;
        transform: scale(1.2);
    }

    .user-id {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.7);
        margin-bottom: 10px;
    }

    .user-level,
    .user-rating {
        font-size: 16px;
        margin-bottom: 5px;
    }

    .highlight {
        color: #ffd700;
        font-weight: bold;
    }

    /* 游戏统计数据样式 */
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 15px;
    }

    .stat-item {
        background-color: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        padding: 15px;
        text-align: center;
        transition: all 0.3s;
        border: 1px solid rgba(255, 215, 0, 0.2);
    }

    .stat-item:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(255, 215, 0, 0.3);
        background-color: rgba(255, 255, 255, 0.15);
    }

    .stat-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: rgba(255, 215, 0, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 10px;
        font-size: 18px;
        color: #ffd700;
    }

    .stat-icon.win {
        background-color: rgba(0, 255, 0, 0.2);
        color: #00ff00;
    }

    .stat-icon.loss {
        background-color: rgba(255, 0, 0, 0.2);
        color: #ff5757;
    }

    .stat-icon.streak {
        background-color: rgba(255, 165, 0, 0.2);
        color: orange;
    }

    .stat-value {
        font-size: 22px;
        font-weight: bold;
        margin-bottom: 5px;
    }

    .stat-label {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.7);
    }

    /* 游戏记录样式 */
    .match-history {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .match-item {
        display: flex;
        align-items: center;
        padding: 12px 15px;
        border-radius: 8px;
        background-color: rgba(255, 255, 255, 0.1);
        transition: all 0.3s;
    }

    .match-item:hover {
        transform: translateX(5px);
        background-color: rgba(255, 255, 255, 0.15);
    }

    .match-item.win {
        border-left: 4px solid #00ff00;
    }

    .match-item.loss {
        border-left: 4px solid #ff5757;
    }

    .match-result {
        font-weight: bold;
        width: 60px;
    }

    .match-item.win .match-result {
        color: #00ff00;
    }

    .match-item.loss .match-result {
        color: #ff5757;
    }

    .match-details {
        flex: 1;
        display: flex;
        flex-direction: column;
    }

    .match-opponent {
        font-size: 16px;
    }

    .match-score {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.7);
    }

    .match-rating {
        font-weight: bold;
        width: 50px;
        text-align: right;
    }

    .match-item.win .match-rating {
        color: #00ff00;
    }

    .match-item.loss .match-rating {
        color: #ff5757;
    }

    .history-footer {
        display: flex;
        justify-content: space-between;
        margin-top: 15px;
    }

    .history-btn,
    .refresh-btn {
        padding: 8px 15px;
        font-size: 14px;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s;
        background-color: rgba(255, 255, 255, 0.1);
        color: #fff;
        border: 1px solid rgba(255, 215, 0, 0.3);
    }

    .history-btn:hover,
    .refresh-btn:hover {
        background-color: rgba(255, 215, 0, 0.2);
        transform: translateY(-2px);
    }

    .refresh-btn {
        display: flex;
        align-items: center;
        gap: 5px;
    }

    /* 底部按钮 */
    .profile-footer {
        display: flex;
        justify-content: flex-end;
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid rgba(255, 215, 0, 0.3);
    }

    .back-btn {
        padding: 12px 20px;
        font-size: 16px;
        font-weight: bold;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s;
        border: none;
        background-color: #666;
        color: #fff;
    }

    .back-btn:hover {
        background-color: #555;
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    }

    /* 对话框样式 */
    :deep(.edit-dialog) {
        background-color: rgba(0, 0, 0, 0.8);
        border-radius: 10px;
        border: 1px solid rgba(255, 215, 0, 0.3);
    }

    .form-item {
        margin-bottom: 20px;
    }

    .form-item label {
        display: block;
        margin-bottom: 8px;
        font-size: 16px;
        color: #ffd700;
    }

    .form-item input {
        width: 100%;
        background-color: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 215, 0, 0.3);
        border-radius: 6px;
        padding: 12px 15px;
        color: black;
        font-size: 16px;
        transition: all 0.3s;
        box-sizing: border-box;
    }

    .form-item input:focus {
        outline: none;
        border-color: #ffd700;
        box-shadow: 0 0 8px rgba(255, 215, 0, 0.6);
    }

    .dialog-footer {
        display: flex;
        justify-content: center;
        gap: 20px;
        padding-top: 10px;
    }

    .dialog-btn {
        padding: 10px 20px;
        border-radius: 6px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        transition: all 0.3s;
        border: none;
    }

    .dialog-btn.cancel {
        background-color: #666;
        color: white;
    }

    .dialog-btn.cancel:hover {
        background-color: #555;
    }

    .dialog-btn.confirm {
        background-color: #ffd700;
        color: #000;
    }

    .dialog-btn.confirm:hover {
        background-color: #ffc000;
        box-shadow: 0 5px 15px rgba(255, 215, 0, 0.4);
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(-20px) scale(0.95);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }

    /* 头像上传对话框 */
    .avatar-preview {
        width: 150px;
        height: 150px;
        margin: 0 auto 20px;
        border-radius: 50%;
        overflow: hidden;
        border: 3px solid #ffd700;
        box-shadow: 0 0 15px rgba(255, 215, 0, 0.3);
    }

    .avatar-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .file-input {
        padding: 8px;
        background-color: rgba(255, 255, 255, 0.1);
        border-radius: 4px;
        width: 100%;
        color: white;
    }

    .upload-tips {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.6);
        margin-top: 8px;
        text-align: center;
    }
</style>
